import json
import sys

from rectpack import *

AlgoList = ['MaxRectsBl',
            # 'MaxRectsBssf',
            # 'MaxRectsBaf',
            # 'MaxRectsBlsf',
            # 'SkylineBl',
            # 'SkylineBlWm',
            # 'SkylineMwf',
            # 'SkylineMwfl',
            # 'SkylineMwfWm',
            # 'SkylineMwflWm',
            # 'GuillotineBssfSas',
            # 'GuillotineBssfLas',
            # 'GuillotineBssfSlas',
            # 'GuillotineBssfLlas',
            # 'GuillotineBssfMaxas',
            # 'GuillotineBssfMinas',
            # 'GuillotineBlsfSas',
            # 'GuillotineBlsfLas',
            # 'GuillotineBlsfSlas',
            # 'GuillotineBlsfLlas',
            # 'GuillotineBlsfMaxas',
            # 'GuillotineBlsfMinas',
            # 'GuillotineBafSas',
            # 'GuillotineBafLas',
            # 'GuillotineBafSlas',
            # 'GuillotineBafLlas',
            # 'GuillotineBafMaxas',
            # 'GuillotineBafMinas'
            ]


def go_rectpack(draw_width=127, rectangles=None):
    if rectangles is None:
        rectangles = []

    rate = 0
    packers = newPacker()
    # 循环算法
    for i in AlgoList:
        yNum = 0
        imageArea = 0
        # 按钮初始化
        packer = newPacker(pack_algo=globals()[i])
        packer.add_bin(draw_width, 5000)

        # 添加待打包的矩形
        for r in rectangles:
            imageArea += int(r[0]) * int(r[1])
            packer.add_rect(*r)
        # 运行装箱算法，获取打包结果
        packer.pack()

        if len(rectangles) > len(packer.rect_list()):
            continue
        print("number", len(packer.rect_list()), "alo", i)
        # 循环单个算法的返回结果也就是
        for b in packer:
            for r in b:
                if r.y + r.height > yNum:
                    yNum = r.y + r.height
                    nowRate = (imageArea / (yNum * draw_width)) * 100
                    print("alo rate:", nowRate)
                    if nowRate > rate:
                        print("now rate:", nowRate)
                        rate = nowRate
                        packers = packer

        print("ImageArea..", imageArea)
        print("rate..", rate)
        print("yNum", str(yNum))
        print("==================================")

        print(packers.rect_list())


if __name__ == "__main__":
    data = sys.argv
    if len(data) >= 2:
        rect_list = []
        list = data[1].split(",")
        for item in list:
            items = item.split(":")
            wh = int(items[0]), int(items[1])
            rect_list.append(wh)
        go_rectpack(rectangles=rect_list)
